#-*- coding: utf-8 -*-

import PySimpleGUI as sg
import os.path
import random
import moviepy.editor as mp

import const
from crop import crop_video
from add_watermark import add_watermark
from ai import find_video_scenes, get_better_scenes_group
from file import new_folder
from tool import random_char
from compress import Compress_Pic_or_Video
from effect import set_video_speed, set_video_volumn

#定义一些常量
const.WINDOW_NAME = "PVA"
const.VIDEO_FOLDER = "-FOLDER-"
const.START = "-START-"
const.REMOVE_WATERMARK = "-REMOVE_WATERMARK-"
const.AI = "-AI-"
const.COMPRESS = "-COMPRESS-"
const.ADD_WATERMARK = "-ADD_WATERMARK-"
const.WATERMARK_TEXT = "-WATERMARK_TEXT-"
const.FILE_LIST = "-FILE_LIST-"
const.AI_THRESHOLD = "-AI_THRESHOLD-"
const.VIDEO_MIN_DURATION = "-VIDEO_MIN_DURATION-"

#Processing Video Automaticly(PVA)
class PVA():
    def __init__(self):
        self._init_attr()
        self._layout()

        self.window = sg.Window(const.WINDOW_NAME, self.layout)

        self._handle_event()
        self.window.close()
    
    def _init_attr(self):
        self.layout = None
        self.window = None
        self.is_compress = False
        self.is_ai = False
        # self.isAddWatermark = False
        # self.watermarkText = ""
        self.video_folder_path = None
        self.videos = None
        self.threshold = 70
        self.min_duraiton = 4
        self.is_run = False
        self.target_folder = None
    
    def start(self):
        if self.is_run:
            return
        self.is_run = True

        #获取面板上的值
        self._get_attr_from_panel()

        if self.is_ai and self.is_compress:
            self._do_ai()
            self._do_compress(True)

        elif self.is_ai:
            self._do_ai()

        elif self.is_compress:
            self._do_compress()

        self.is_run = False

    def _do_ai(self):
        # 新建一个文件夹
        self.target_folder = os.path.join(self.video_folder_path, "AI_" + random_char(10))
        new_folder(self.target_folder)

        #循环对视频进行处理
        for video_path in self.videos:
            temp_video_path = video_path
            scenes_info = find_video_scenes(temp_video_path, self.threshold, self.min_duraiton)
            scenes_group = get_better_scenes_group(scenes_info, 3)
            # 加载视频
            origin_video = mp.VideoFileClip(temp_video_path)
            temp_video = [
                origin_video.subclip(d["start"], d["end"]) for d in scenes_info
            ]
            vs = []
            for group in scenes_group:
                vs.append(mp.concatenate_videoclips([temp_video[i] for i in group]))
            # 乱序
            random.shuffle(vs)
            temp_video = mp.concatenate_videoclips(vs)
            
            #添加视频效果
            temp_video = self._add_video_effect(temp_video)
            # crop
            temp_video = self._do_crop_video(temp_video)
            #添加水印
            temp_video = self._do_add_watermark(temp_video)
            #保存视频
            self._save_video(
                temp_video, 
                os.path.join(self.target_folder, "ai" + os.path.basename(temp_video_path))
            )

    def _do_compress(self, is_remove_origin_file=False):
        #压缩视频文件
        folder = self.target_folder if self.target_folder else self.video_folder_path
        video_names = [
            # os.path.join(folder, f)
            f
            for f in os.listdir(folder)
            if os.path.isfile(os.path.join(folder, f))
            and f.lower().endswith((".mp4"))
        ]
        #实例化
        compress_video = Compress_Pic_or_Video()
        for video_name in video_names:
            compress_video.set_video(folder, video_name, "compress_" + video_name)
            compress_video.compress_video_anyc()
            print(folder, video_name, "compress_" + video_name)
            if is_remove_origin_file:
                os.remove(os.path.join(folder, video_name))

    def _do_add_watermark(self, video):
        return add_watermark(video)

    def _do_crop_video(self, video):
        return crop_video(video, 1.2)
    
    def _add_video_effect(self, video):
        # 加大声音和加速
        return set_video_volumn(set_video_speed(video, 1.1), 2)


    def _save_video(self, video, video_path):
        video.write_videofile(
            video_path, 
            codec="libx264", 
            bitrate="10000000", 
            audio_codec="aac", # 加上声道才会有声音
            threads=4
        )

    def _get_attr_from_panel(self):
        _event, values = self.window.read()
        self.video_folder_path = values[const.VIDEO_FOLDER]
        self.is_ai = values[const.AI]
        # self.is_compress = values[const.COMPRESS]
        self.videos = self._get_file_list(values)
        self.threshold = int(values[const.AI_THRESHOLD])
        self.min_duraiton = int(values[const.VIDEO_MIN_DURATION])  

    def _get_file_list(self, values):
        folder = values[const.VIDEO_FOLDER]
        try:
            # Get list of files in folder
            fileList = os.listdir(folder)
        except:
            fileList = []  
        return [
            os.path.join(folder, f)
            for f in fileList
            if os.path.isfile(os.path.join(folder, f))
            and f.lower().endswith((".mp4"))
        ]

    def _handle_event(self):
        # Run the Event Loop
        while True:
            event, values = self.window.read()
            if event == "Exit" or event == sg.WIN_CLOSED:
                break
            # Folder name was filled in, make a list of files in the folder
            if event == const.VIDEO_FOLDER:
                self.window[const.FILE_LIST].update(self._get_file_list(values))
            elif event == const.START:
                self.start()

    def _layout(self):
        file_list_column = [
            [
                sg.Text("请选择视频文件夹:"),
                sg.In(size=(25, 1), enable_events=True, key=const.VIDEO_FOLDER),
                sg.FolderBrowse(button_text="选择"),
            ],
            [
                sg.Text("请选择视频操作:"),
                # sg.Checkbox('去除水印', key=const.REMOVE_WATERMARK), 
                sg.Checkbox('智能处理', key=const.AI), 
                # sg.Checkbox('压缩', key=const.COMPRESS)
            ],
            [
                # sg.Checkbox('添加水印', key=const.ADD_WATERMARK),
                sg.Text("设置视频分割阈:"),
                sg.In(size=(25, 1), enable_events=True, key=const.AI_THRESHOLD, default_text=self.threshold),
            ],
            [
                sg.Text("设置最短视频视频:"),
                sg.In(size=(25, 1), enable_events=True, key=const.VIDEO_MIN_DURATION, default_text=self.min_duraiton),
            ],
            [
                sg.Button("START", key=const.START)
            ],
            [
                sg.Listbox(
                    values=[], enable_events=True, size=(60, 40), key=const.FILE_LIST
                )
            ],
        ]
        # For now will only show the name of the file that was chosen
        image_viewer_column = [
            [sg.Text("进度展示:")],
            [sg.Text(size=(40, 1), key="-TOUT-")],
            # [sg.Image(key="-IMAGE-")],
        ]
        # ----- Full layout -----
        self.layout = [
            [
                sg.Column(file_list_column),
                sg.VSeperator(),
                sg.Column(image_viewer_column),
            ]
        ]
        


if __name__ == "__main__":
    pva = PVA()